package com.load.factories;

import static com.load.utils.DateUtil.*;
import static com.load.utils.MathUtil.*;

import java.util.*;

import org.tmatesoft.svn.core.*;

import com.database.objects.*;
import com.load.objects.MySVNDirEntry;

public class CommitFactory {

	public static Commit createCommit(Project project, SVNLogEntry entry) {
		Long number = entry.getRevision();
		String date = formatString(entry.getDate());
		Status status = defineStatus(entry);
		Developer developer = project.getDeveloperByName(entry.getAuthor());

		if (developer != null) {
			Commit commit = new Commit(number, date, status, developer);
			return commit;
		}
		return null;
	}

	private static Status defineStatus(SVNLogEntry entry) {
		Map<Status, Integer> statusMap = initializeMap();
		Map<?, ?> changedPaths = entry.getChangedPaths();
		for (Object keyPath : changedPaths.keySet()) {
			SVNLogEntryPath entryPath = (SVNLogEntryPath) changedPaths.get(keyPath);
			Status status = Status.createStatus("" + entryPath.getType());
			Integer counter = statusMap.get(status) + 1;
			statusMap.put(status, counter);
		}
		return max(statusMap);
	}

	private static Map<Status, Integer> initializeMap() {
		Map<Status, Integer> types = new HashMap<Status, Integer>();
		types.put(Status.ADD, 0);
		types.put(Status.MODIFY, 0);
		types.put(Status.DELETE, 0);
		types.put(Status.REPLACE, 0);
		types.put(Status.UNKNOWN, 0);
		return types;
	}

	public static Commit createCommit(MySVNDirEntry entry) {
		Long number = entry.getRevision();
		String date = formatString(entry.getDate());

		return new Commit(number, date, null, null);
	}

}